/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2019年05月28日
*   描    述：
*   Copyright (C) 2019 All rights reserved.
*   
================================================================*/


#include <iostream>
#include <vector>

using namespace std;
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n);
        for(int i = 0; i < n; i++){
            res[i].resize(n);
        }

        int now = 1;
        int left = 0, right = n - 1, up = 0, down = n - 1;
        while( left <= right && up <= down ){
            for(int i = left; i <= right; i++){//从左到右
                res[up][i] = now++;
            }
            up++;

            for(int i = up; i <= down; i++){
                res[i][right] = now++;
            }
            right--;

            if(up <= down){
                for(int i = right; i >= left; i--){
                    res[down][i] = now++;
                }
                down--;
            }

            if( left <= right ){
                for(int i = down; i >= up; i--){
                    res[i][left] = now++;
                }
                left++;
            }
        }

        return res;
    }
};
